<?php
/**
* Cart  Controller 
*/
class Cart extends CI_Controller {
	private $data = array();
	
	function __construct() {
	    parent::__construct();
	}
	
	public function index() {
		// Loads the cart contetns to an array.
		$this->data['cart'] = $this->cart->contents();
		
		//  Gets the totalt items count from the cart.
		$this->data['cartTotal'] = $this->cart->total_items();
		
		// Load the view with the new data.
		$this->load->view('cart', $this->data );
	}
	
	/**
	* Update
	* Updates the cart with new information regarding items.
	*/
	public function Update() {
	    for ( $i = 1; $i <= $this->cart->total_items(); $i++ ) {
		    
			$item = $this->input->post( $i );
			$data = array(
			    'rowid' => $item['rowid'],
				'qty' => $item['qty']
			);
			
			$this->cart->update( $data );
		}
		
        redirect( 'cart/index' );
	}
	
	/**
	* Clear
	* Destorys the current cart.
	*/
	public function Clear() {
	    $this->cart->destroy();
		redirect( 'index/index' );
	}
	
	/**
	* AddToCart
	* Adds a new product to the cart items.
	*/
	public function AddToCart() {
		if ( $this->input->post( 'ProductID' ) ) {
			
			// Load the products_model and auto-connects to the database.
			$this->load->model( 'products_model', '', TRUE );
			
			// Retrives the item from the database with the specified ProductID.
		    $this->data['product'] = $this->products_model->GetProductById( $this->input->post( 'ProductID' ) );
			
			// Creates an array with the new item to store in the Cart.
			$product = array(
                'id' => $this->input->post( 'ProductID' ),
                'qty' => $this->input->post( 'product_amount' ),
                'price' => $this->data['product'][0]['Price'],
                'name' => $this->data['product'][0]['Name']
		    );
			
			// Inserts the item to the Cart (Returns rowid if successfull).
			$this->cart->insert( $product );
		}
		
		redirect( 'index/index' );
	}
}